package com.it;

public class PolymorphicDemo {
    public static void main(String[] args) {
        //演示向上造型
        //这里注意dog1拥有所有的属性和方法，包括继承和实现的接口
        Dog dog1 = new Dog("小白", 1, "白");//狗是狗

        //这里注意dog2只能拥有Animal的属性和方法，因为dog2不能大于父类Animal
        Animal dog2 = new Dog("小白", 1, "白");//狗是动物

        //这里注意dog3只能拥有Swin的方法，因为dog3不能大于接口Swin
        Swin dog3 = new Dog("小白", 1, "白");//狗会游泳


        System.out.println("-----------");

        Master master = new Master();
        Dog dog = new Dog("小白", 1, "白");//狗是狗
        Fish fish = new Fish("小鱼", 1, "金");
        Chick chick = new Chick("小黑", 1, "黑");

        master.feed(dog);//这里在传参的时候，系统自动做了向上造型,也就是类型转换，小的自动转大的 (Animal>dog - fish - chick)
        master.feed(fish);
        master.feed(chick);

        System.out.println("-----------");


        //创建动物数组，可以容纳多种不同类型的动物
        Animal[] animals = new Animal[5];
        animals[0] = new Dog("小白", 1, "白");
        animals[1] = new Dog("小白", 3, "白");
        animals[2] = new Fish("小金", 2, "金");
        animals[3] = new Fish("小鱼", 1, "金");
        animals[4] = new Chick("小黑", 2, "黑");

        //遍历数组，取出每个动物的name
        for (int i = 0; i < animals.length; i++) {
            System.out.println(animals[i].name);
            animals[i].eat();//每个动物吃饭
            animals[i].drink();//每个动物喝水
        }
        System.out.println("----------------------------------------------------");

        //遍历，让每个动物都有自己的方法
        for (int i = 0; i < animals.length; i++) {
            //先判断是不是Dog类
            if (animals[i] instanceof Dog) {
                Dog dogs1 = (Dog) animals[i];//强转为Dog类
                dogs1.lookHome();//Dog子类的特有方法
            }
            if (animals[i] instanceof Fish) {
                Fish fish1 = (Fish) animals[i];//强转为Fish类
                fish1.eat();
            }
            if (animals[i] instanceof Chick) {
                Chick chick1 = (Chick) animals[i];//强转为Chick类
                chick1.layEggs();//Chick子类的特有方法
            }
            if (animals[i] instanceof Swin) {
                Swin s = (Swin) animals[i];//这里适用于所有实现Swin接口的(会游泳的)
                s.swin();
            }
        }

        System.out.println("----------------------------------------------------");

        Dog dd = (Dog) animals[0];//这里就是强转，把Animal类型转为Dog类型
        dd.lookHome();

        //在强转时，一般会用instanceof方法来做判断是否是某个类型，返回的只有true或false
        Animal o = new Dog();
        System.out.println(o instanceof Dog);//true
        System.out.println(o instanceof Animal);//true
        System.out.println(o instanceof Swin);//true
        System.out.println(o instanceof Fish);//false
        System.out.println(o instanceof Chick);//false

        if (o instanceof Fish) {
            Fish f = (Fish) o;
        } else {
            System.out.println("o不是Fish类型");
        }


    }
}
